//
//  HistogramView.m
//  AirQuality
//
//  Created by Mac on 15/12/29.
//  Copyright © 2015年 Po. All rights reserved.
//

#import "HistogramView.h"
#import "CollectionViewCell.h"
#import "DrayImage.h"
#import "BorederView.h"

#define HisgromWidth 7
#define TableViewHeight 110

@interface HistogramView ()<UITableViewDelegate,
                            UITableViewDataSource>

@property (strong, nonatomic) UITableView * tableView;
@property (strong, nonatomic) UICollectionView * collectionView;
@property (strong, nonatomic) UISegmentedControl * segment;
@property (strong, nonatomic) NSArray * dataArr;
@property (strong, nonatomic) NSString * max,* dayMax,* hourMax, * yearMax;
@property (strong, nonatomic) UIScrollView * scrollView;
@property (strong, nonatomic) UIView * instructionView;  //提示框
@property (strong, nonatomic) DrayImage * triangleImage; //三角形
//@property (strong, nonatomic) BorederView * borderView;   //边框
@property (strong, nonatomic) NSMutableArray * allDataArr , * allTimeArr; //所有数据
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSArray * dayArr, * dataSouce, * yearArr , * monthArr;
@property (strong, nonatomic) UILabel * countLable;
@property (strong, nonatomic)  NSString * key;
@property (assign) CGFloat widthOff,dayOff,hourOff;
@property (assign) NSInteger flag,isFirstTap,dayScroll;
@property (strong, nonatomic) UIView * lastView, * twoView, *horizontalView;                         // 矩形框
@property (assign) CGFloat allWidth;        //矩形框移动距离
@property (strong, nonatomic) NSMutableArray * viewArray ,* indexArray ;  //存柱状图
@property (assign,nonatomic) NSInteger test;
@property(assign)  CGFloat lastPosition ;
@property (strong, nonatomic) NSMutableDictionary * viewDic;
@property (strong, nonatomic) NSArray * allKeyArr;
@property (strong, nonatomic) NSMutableArray * firstHistog;
@property (assign) NSInteger distance;
@property (strong, nonatomic) NSString * rightString ,* keyStr;
@property (strong, nonatomic) NSMutableArray * Inum;    //I值
@property (assign) CGRect traingRect;

@end

@implementation HistogramView

- (instancetype)initWithFrame:(CGRect)frame withData:(NSDictionary *)data withDayArr:(NSDictionary *)dayArr
{
    if ([super initWithFrame:frame]) {
        _max = data[@"max"];
        _hourMax = data[@"max"];
        _yearMax = dayArr[@"max"];
        NSArray * keyarray = [data allKeys];
        _dayArr = [dayArr allValues];
        _allWidth = 0;
        _viewArray = [NSMutableArray array];
        _indexArray = [NSMutableArray array];
        _viewDic = [NSMutableDictionary dictionary];
        _firstHistog = [NSMutableArray array];
        _allKeyArr = [NSArray array];
        _allDataArr = [NSMutableArray array];
        _allTimeArr = [NSMutableArray array];
        _monthArr = [NSArray array];
        for (NSString * string in keyarray) {
            if (![string isEqualToString:@"max"]) {
                _key = string;
            }
        }
        NSDictionary * changeDic = @{@"AQI":@"AQI",@"PM2_5":@"PM",@"PM10":@"PM₁₀",@"O3":@"O₃",@"SO2":@"SO₂",@"NO2":@"NO₂",@"CO":@"CO"};
       _keyStr = changeDic[_key];
        if (!_keyStr) {
            _keyStr = _key;
        }
        _yearArr = dayArr[_key];
        _dataArr = data[_key];
        _monthArr = [data[_key] copy];
        _allDataArr = [_dataArr[0] mutableCopy];
        _allTimeArr = [_dataArr[1] mutableCopy];
        NSArray * nullArr = _dataArr[2];
        if (nullArr.count != 0) {
           _Inum = [_dataArr[2] mutableCopy];
        }
        if ([RJUserData defaultRJUserData].isYearData) {
            _dataSouce = _yearArr[0];
            _allDataArr = [_yearArr[0] mutableCopy];
            _allTimeArr = [_yearArr[1] mutableCopy];
            _Inum = [_yearArr[2] mutableCopy];
        }
        [self addEmptyHisgrom:ScreenWidth/HisgromWidth];//添加空白 item
        _dayMax = dayArr[@"max"];
        self.backgroundColor = [UIColor whiteColor];
        [self inittableView];
        [self getSwitchView];
        [self getTriangleImageWithFram:CGRectMake(ScreenWidth-20, 160, 30, 30)];
        _traingRect = CGRectMake(ScreenWidth-20, 160, 30, 30);
        if ([_key isEqualToString:@"AQI"]) {
             [self getinstructionViewWithFrame:CGRectMake(ScreenWidth-185+15+10+3+1, 170, 180-25, 16)];
        }else{
            [self getinstructionViewWithFrame:CGRectMake(ScreenWidth-185+3, 170, 180, 16)];
        }
        if ([RJUserData defaultRJUserData].isYearData) {
            [self getAllYearOffset];
        }else{
            [self getAllHourOffset];
        }
    }
    return self;
}

- (void)inittableView
{
    if (!_allDataArr) {
        return;
    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake((ScreenWidth-TableViewHeight)/2, -(ScreenWidth-TableViewHeight)/2+50, TableViewHeight, ScreenWidth)];
    _tableView.transform = CGAffineTransformMakeRotation(M_PI/2*3);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.bounces = NO; //取消弹簧效果
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_allDataArr.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self addSubview:_tableView];
}

- (void)initailizeCollection
{

}

- (void)getSwitchView
{
    if (!_segment) {
        NSArray * segArr = @[@"小时数据",@"日数据"];
        _segment = [[UISegmentedControl alloc] initWithItems:segArr];
        _segment.frame = CGRectMake(100, 10, ScreenWidth-200, 20);
        if ([RJUserData defaultRJUserData].isYearData) {
           _segment.selectedSegmentIndex = 1;
        }else{
          _segment.selectedSegmentIndex = 0;
        }
        _segment.momentary = NO;
        _segment.tintColor = SysMainColor;
        [_segment addTarget:self action:@selector(segChange:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:_segment];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _allDataArr.count-1) {
        return 0.5;
    }
    return HisgromWidth;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * collIdentifer = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:collIdentifer];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:collIdentifer];
    }
    for (UIView * view in [cell.contentView subviews]) {
        [view removeFromSuperview];
    }
    if (_isFirstTap) {
        _max = _dayMax;
    }else{
        _max = _hourMax;
    }
//    NSLog(@"%ld",_viewArray.count);
    //添加上下灰色线条
    UIView * bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1,HisgromWidth)];
    bottomLineView.backgroundColor = GetRGBColor(153, 153, 153, 1);
    [cell.contentView addSubview:bottomLineView];
    UIView * topLimeView = [[UIView alloc] initWithFrame:CGRectMake(TableViewHeight-1, 0, 1, HisgromWidth)];
    topLimeView.backgroundColor = GetRGBColor(153, 153, 153, 1);
    [cell.contentView addSubview:topLimeView];
    [_firstHistog addObject:[NSString stringWithFormat:@"%ld", (long)indexPath.row]];
    NSDictionary * exchangeDic = @{@"AQI":@"AQI",@"PM":@"PM2_5",@"PM₁₀":@"PM10",@"O₃":@"O3",@"SO₂":@"SO2",@"NO₂":@"NO2",@"CO":@"CO"};
    NSString * type;
    type = exchangeDic[_key];
    if (!type) {
        type = _key;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CGFloat count = 90.0/[_max floatValue];
    CGFloat hight = [_allDataArr[indexPath.row] floatValue]*count;
    CGFloat Ivalue = [_Inum[indexPath.row] floatValue];
    if (isnan(hight)) {
        hight = 0.0;
    }
    UIView * view = [[UIView alloc] init];
    view.tag = indexPath.row;
    view.frame = CGRectMake(1, 0.5, hight, HisgromWidth-1);
//    view.backgroundColor = [RJTools getColorWithAirNum:value  type:type alpha:1];
    view.backgroundColor =[RJTools getColorWithAirINum:Ivalue];
    [cell.contentView addSubview:view];
    cell.backgroundColor = [UIColor clearColor];
    NSString * indexStr = [NSString stringWithFormat:@"%ld",indexPath.row];
    NSArray * keyArr = [_viewDic allKeys];
    if ([keyArr indexOfObject:indexPath] == NSNotFound) {
        [_viewDic setObject:view forKey:indexStr];
    }
    if (!_test) {
        if (indexPath.row == _allDataArr.count-1) {
            UIView * grayView = _viewDic[[NSString stringWithFormat:@"%ld",indexPath.row-2]];
            grayView.layer.borderColor = [UIColor grayColor].CGColor;
            grayView.layer.borderWidth = 2.0;
            _lastView = grayView;
            [self setCountLableCount:grayView.tag];
            _test = YES;
        }
        return cell;
    }
    if (indexPath.row < _lastView.tag) {
        if (DeviceType < 6) {
            _triangleImage.frame = CGRectMake(ScreenWidth-20, 160, 30, 30);
        }else if(DeviceType > 6){
            _triangleImage.frame = CGRectMake(ScreenWidth-20+4, 160, 30, 30);
        }else if (DeviceType <5){
            _triangleImage.frame = CGRectMake(ScreenWidth-20, 160, 30, 30);
        }else{
            _triangleImage.frame = CGRectMake(ScreenWidth-20+2, 160, 30, 30);
        }
        NSString * lastIndex = [NSString stringWithFormat:@"%ld",indexPath.row+(NSUInteger)ScreenWidth/HisgromWidth-1];
        _lastView.layer.borderWidth = 0.0;
        UIView * grayView = _viewDic[lastIndex];
        grayView.layer.borderColor = [UIColor grayColor].CGColor;
        grayView.layer.borderWidth = 2.0;
        _lastView = grayView;
        [self setCountLableCount:grayView.tag];
//        NSLog(@"%ld",grayView.tag);
    }else{
        if (DeviceType > 6) {
            _triangleImage.frame = CGRectMake(ScreenWidth-20+4, 160, 30, 30);
        }else if (DeviceType>4&&DeviceType<6){
            _triangleImage.frame = CGRectMake(ScreenWidth-20+2, 160, 30, 30);
        }else if (DeviceType < 5){
            _triangleImage.frame = CGRectMake(ScreenWidth-20, 160, 30, 30);
        }else{
            _triangleImage.frame = CGRectMake(ScreenWidth-20+2, 160, 30, 30);
        }
        NSString * lastIndex = [NSString stringWithFormat:@"%ld",_lastView.tag+1];
        _lastView.layer.borderWidth = 0.0;
        UIView * grayView = _viewDic[lastIndex];
        grayView.layer.borderColor = [UIColor grayColor].CGColor;
        grayView.layer.borderWidth = 2.0;
        _lastView = grayView;
//        NSLog(@"%ld",grayView.tag);
        [self setCountLableCount:grayView.tag];
        if (indexPath.row == _allDataArr.count-1) {
            _lastView.layer.borderWidth = 0.0;
            UIView * grayView = _viewDic[[NSString stringWithFormat:@"%ld",indexPath.row-2]];
            grayView.layer.borderColor = [UIColor grayColor].CGColor;
            grayView.layer.borderWidth = 2.0;
            _lastView = grayView;
            [self setCountLableCount:grayView.tag];
            return cell;
        }
    }
    return cell;
}


#pragma mark --getinstructionView
- (void)getinstructionViewWithFrame:(CGRect)frame
{
    if (!_instructionView) {
        _instructionView = [[UIView alloc] initWithFrame:frame];
        _instructionView.backgroundColor = SysMainColor;
        _instructionView.layer.cornerRadius = 4.0;
        _instructionView.layer.masksToBounds = YES;
        _countLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 180, 17)];
        _countLable.font = [UIFont systemFontOfSize:10];
        _countLable.textColor = [UIColor whiteColor];
        [_instructionView addSubview:_countLable];
        [self addSubview:_instructionView];
    }
}

- (void)setCountLableCount:(NSInteger)count
{
    if (count > _allDataArr.count-1 || count < 0) {
        return;
    }
    NSString * string;
    if ([_keyStr isEqualToString:@"PM2.5"] || [_keyStr isEqualToString:@"PM"]) {
        string = @"PM₂.₅";
    }else if ([_keyStr isEqualToString:@"PM"]){
    
    }else{
        string = [NSString stringWithFormat:@"  %@",_keyStr];
    }
    if ([_key isEqualToString:@"AQI"]) {
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@",_allTimeArr[count],string,@"=",_allDataArr[count]];
    }else if ([_key isEqualToString:@"CO"]){
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@%@",_allTimeArr[count],string,@"=",_allDataArr[count],@"mg/m³"];
    }else{
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@%@",_allTimeArr[count],string,@"=",_allDataArr[count],@"µg/m³"];
    }
}

- (void)getTriangleImageWithFram:(CGRect)frame
{
    if (!_triangleImage) {
        _triangleImage = [[DrayImage alloc] initWithFrame:frame];
        _triangleImage.backgroundColor = [UIColor clearColor];
        [self addSubview:_triangleImage];
    }
}


- (void)segChange:(UISegmentedControl *)sender
{
    _test = NO;
    _viewArray = [NSMutableArray array];
    _firstHistog = [NSMutableArray array];
    if (sender.selectedSegmentIndex == 1) {
        [RJUserData defaultRJUserData].isYearData = YES;
        _isFirstTap = YES;
        _dataSouce = _yearArr[0];
        _allDataArr = [_yearArr[0] mutableCopy];
        _allTimeArr = [_yearArr[1] mutableCopy];
        _Inum = [_yearArr[2] mutableCopy];
        [_tableView removeFromSuperview];
        _tableView = nil;
        [self inittableView];
        [self addEmptyHisgrom:ScreenWidth/HisgromWidth];
        [self getAllYearOffset];
        [_tableView reloadData];
    }else if (sender.selectedSegmentIndex == 0){
        _isFirstTap = NO;
        [RJUserData defaultRJUserData].isYearData = NO;
        _dataSouce = [_dataArr[0] mutableCopy];
        _allDataArr = [_dataArr[0] mutableCopy];
        _allTimeArr = [_dataArr[1] mutableCopy];
        _Inum = [_dataArr[2] mutableCopy];
        [_tableView removeFromSuperview];
        _tableView = nil;
        [self inittableView];
        [self addEmptyHisgrom:ScreenWidth/HisgromWidth];
        [self getAllHourOffset];
        [_tableView reloadData];
    }
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_allDataArr.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


- (void)getAllHourOffset
{
    for (NSInteger i = 0; i < _allTimeArr.count; i ++) {
        NSString * timeStr = _allTimeArr[i];
        NSString * subStr;
        if (timeStr.length == 1) {
            continue;
        }
        subStr = [timeStr substringWithRange:NSMakeRange(timeStr.length-5, 5)];
        if ([subStr isEqualToString:@"00:00"]) {
            UIView * view = [[UIView alloc] init];
            view.frame = CGRectMake(0, i*HisgromWidth, TableViewHeight, 1);
            view.backgroundColor = [UIColor grayColor];
            [_tableView addSubview:view];
            UILabel * timeLable = [[UILabel alloc] initWithFrame:CGRectMake(TableViewHeight-80+30, i*HisgromWidth+30, 80, 20)];
            timeLable.transform = CGAffineTransformMakeRotation(M_PI/2);
            NSString * lableStr = [timeStr substringToIndex:10];
            timeLable.text = lableStr;
            timeLable.font = [UIFont systemFontOfSize:12];
            [_tableView addSubview:timeLable];
        }
    }
    
}

- (void)getAllYearOffset
{
    for (NSInteger i = 0; i < _allTimeArr.count; i ++){
        NSString * timeStr = _allTimeArr[i];
        NSString * subStr = [timeStr substringWithRange:NSMakeRange(timeStr.length-2, 2)];
        if ([subStr isEqualToString:@"01"]) {
            UIView * view = [[UIView alloc] init];
            view.frame = CGRectMake(0, i*HisgromWidth, TableViewHeight, 1);
            view.backgroundColor = [UIColor grayColor];
            [_tableView addSubview:view];
            UILabel * timeLable = [[UILabel alloc] initWithFrame:CGRectMake(TableViewHeight-80+30, i*HisgromWidth+30, 80, 20)];
            timeLable.transform = CGAffineTransformMakeRotation(M_PI/2);
            NSString * lableStr = [timeStr substringToIndex:10];
            timeLable.text = lableStr;
            timeLable.font = [UIFont systemFontOfSize:12];
            [_tableView addSubview:timeLable];
        }
        
    }
}

#pragma mark - addEmptyHisgrom
- (void)addEmptyHisgrom:(NSInteger)count
{
    for (NSInteger i = 0; i < 2; i ++) {
        [_allDataArr addObject:@"-"];
        [_allTimeArr addObject:@"-"];
        [_Inum addObject:@"0"];
    }
    for (NSInteger i = 0; i < count-1; i ++) {
        [_allDataArr insertObject:@"-" atIndex:0];
        [_allTimeArr insertObject:@"-" atIndex:0];
        [_Inum insertObject:@"0" atIndex:0];
    }
}
@end
